package com.yoga.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yoga.model.Coach;
import com.yoga.model.search.CoachSearchBean;
import com.yoga.service.CoachService;
import com.yoga.service.UploadService;
import com.yoga.utils.AliOSS;
import com.yoga.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @author yan
 * @date 2025/8/15
 */
@RestController
@RequestMapping(value = "/api/v1/coach",produces = MediaType.APPLICATION_JSON_VALUE)
public class coachApi {
    private CoachService coachService;
    private AliOSS aliOSS;
    @Autowired
    public void setAliOSS(AliOSS aliOSS) {
        this.aliOSS = aliOSS;
    }

    @Autowired
    public void setCoachService(CoachService coachService) {
        this.coachService = coachService;
    }
    //查询
    @GetMapping
    public ResponseEntity<JsonResult<?>> findAll(@RequestParam(defaultValue = "1") Integer pageNo,
                                                 @RequestParam(defaultValue = "10") Integer pageSize, CoachSearchBean csb){
        Page<Coach> page = new Page<>(pageNo,pageSize);
        page = this.coachService.findAll(page,csb);
        return ResponseEntity.ok(JsonResult.success(page));
    }

    //删除
    @DeleteMapping
    public ResponseEntity<JsonResult<?>> deleteByIds(@RequestBody Integer[] ids){
        int count = this.coachService.deleteById(List.of(ids));
        if (count == 0){
            return ResponseEntity.ok(JsonResult.fail("删除失败"));
        }else {
            return ResponseEntity.ok(JsonResult.success(count));
        }
    }

    //添加
    @PostMapping
    public ResponseEntity<JsonResult<?>> add(@RequestBody Coach coach){
        boolean flag = this.coachService.add(coach);
        if(flag){
            return ResponseEntity.ok(JsonResult.success(coach));
        }else {
            return ResponseEntity.ok(JsonResult.fail("添加失败"));
        }
    }

    //修改
    @PutMapping
    public ResponseEntity<JsonResult<?>> update(@RequestBody Coach coach){
        boolean flag = this.coachService.update(coach);
        if(flag){
            return ResponseEntity.ok(JsonResult.success(coach));
        }else {
            return ResponseEntity.ok(JsonResult.fail("修改失败"));
        }
    }

    //头像上传
    @PostMapping("/avatar")
    public ResponseEntity<JsonResult<?>> uploadAvatar(MultipartFile file) throws IOException {
        String path = this.aliOSS.upload(file,"coach/");
        return ResponseEntity.ok(JsonResult.success(path));
    }
}
